package com.rppowell.pixie.swing.spriteset;

import com.rppowell.pixie.models.Sprite;
import java.awt.Component;
import java.util.ArrayList;

import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.rppowell.pixie.models.SpriteLibrary;
import com.rppowell.pixie.models.SpriteSet;
import com.rppowell.pixie.swing.PixieUIState;

public class SpriteSetTabbedPane extends JTabbedPane implements ChangeListener {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public SpriteSetTabbedPane() {
        super();
        setTabPlacement(JTabbedPane.BOTTOM);
        setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        addChangeListener(this);
    }

    @Override
    public void stateChanged(ChangeEvent ce) {
        System.out.println(getClass().toString() + ".stateChanged - " + ce);
    }

    public void setSpriteLibrary(SpriteLibrary spriteLibrary) {
        removeAll();
        if (spriteLibrary != null) {
            ArrayList<SpriteSet> spriteSets = spriteLibrary.getSpriteSets();
            for (int i = 0; i < spriteSets.size(); i++) {
                SpriteSet set = spriteSets.get(i);
                addTab(set.getName(), new SpriteSetPanel(set));
            }
        }
    }

    public SpriteSet getSelectedSpriteSet() {
        SpriteSet s = null;
        Component c = getSelectedComponent();
        if (c instanceof SpriteSetPanel) {
            SpriteSetPanel p = (SpriteSetPanel)c;
            s = p.getSpriteSet();
        }
        return s;
    }
    
    public void setPixieUIState(PixieUIState state) {
        if (false) {
            Component c = getSelectedComponent();
            if (c != null && c instanceof SpriteSetPanel) {
                SpriteSetPanel s = (SpriteSetPanel) c;
                s.setPixieUIState(state);
            }
        } else {
            Component[] components = getComponents();
            for (int i = 0; i < components.length; i++) {
                Component c = components[i];
                if (c instanceof SpriteSetPanel) {
                    SpriteSetPanel s = (SpriteSetPanel) c;
                    s.setPixieUIState(state);
                }
            }
        }
    }    
    
    public void setSelectedSpriteInSpriteSet(SpriteSet spriteSet, Sprite sprite) {
        Component[] components = getComponents();
        for (int i = 0; i < components.length; i++) {
            Component c = components[i];
            if (c instanceof SpriteSetPanel) {
                SpriteSetPanel s = (SpriteSetPanel) c;
                if (s.getSpriteSet() == spriteSet) {
                    s.setSelectedSprite(sprite);
                    return;
                }
            }
        }
    }
}
